package main.java.Utiles;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;


public class FlujoEntrada implements Iterable<String>{

	private String delim="\n"; 
	private String nom="";
	
	public FlujoEntrada(){	
	}
	
	public FlujoEntrada(String nom) throws IOException{
		this.nom = nom;
	}
	
	public FlujoEntrada(String nom,String delim) throws IOException{
		this.nom = nom;
		this.delim=delim;
	}
	
	public Iterator<String> iterator(){
		return new IteradorFlujoEntrada(nom,delim);	
	}
	
	private class IteradorFlujoEntrada implements Iterator<String>{
		private BufferedReader bf;
		private Iterator<String> itPalabras;
		private String linea, delims;

		public IteradorFlujoEntrada(String nom, String delims) {
			if (nom.equals(""))
				bf = new BufferedReader(new InputStreamReader(System.in));
			else
				try {
					bf = new BufferedReader(new FileReader(nom));
				} catch (FileNotFoundException e1) {
					System.out.println("No se ha podido acceder al fichero indicado. Se usara la entrada estandar");
					bf = new BufferedReader(new InputStreamReader(System.in));
				}


				this.delims = delims;

				try{
					linea = bf.readLine();
					if(linea!=null) 
						itPalabras = Cadenas.separaElementos(linea, delims).iterator();
				} catch(IOException e) { ; }
		}

		public boolean hasNext() { 	
			return itPalabras!=null  && itPalabras.hasNext(); 
		}

		public String next() {
			String pal = itPalabras.next();
			if(!itPalabras.hasNext()) {
				try {
					linea = bf.readLine();
					if(linea!=null) 
						itPalabras = Cadenas.separaElementos(linea, delims).iterator();
					else
						bf.close();
				} catch(IOException e) { ; }
			}

			return pal;
		}

		public void remove() {}		
	}
}

